package com.ia.aistream.common.type;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ia.aistream.common.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author chenjunsheng
 */
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({Set.class})
public class SetTypeHandler extends BaseTypeHandler<Set<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Set<String> parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public Set<String> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        if(StringUtils.isEmpty(resultSet.getString(columnName))){
            return new HashSet<>();
        }
        return JSON.parseObject(resultSet.getString(columnName), new TypeReference<Set<String>>() {
        });
    }

    @Override
    public Set<String> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        if(StringUtils.isEmpty(resultSet.getString(columnIndex))){
            return new HashSet<>();
        }
        return JSON.parseObject(resultSet.getString(columnIndex), new TypeReference<Set<String>>() {
        });
    }

    @Override
    public Set<String> getNullableResult(CallableStatement statement, int columnIndex) throws SQLException {
        if(StringUtils.isEmpty(statement.getNString(columnIndex))){
            return new HashSet<>();
        }
        return JSON.parseObject(statement.getString(columnIndex), new TypeReference<Set<String>>() {});
    }
}
